package com.dj.study;

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author     ：跟大佳一起学架构
 * @Date       ：Created in 16:16 2024/1/9
 * @Description：虚拟线程与平台线程的对比
 */
public class VirtuallyThread {

    public static void main(String[] args) throws InterruptedException {
        // 简单任务
//        simpleEx();

        //平台线程 与虚拟线程
        // platOrVirtually();

        //平台线程 与虚拟线程
         platOrVirtuallyCompare();

        Thread.sleep(1000000);
    }

    public static void simpleEx(){
        //创建任务
        Thread.startVirtualThread(()->System.out.println("执行任务"));
    }
    public static void platOrVirtually(){
        // 平台线程
        Thread.Builder platformBuilder = Thread.ofPlatform().name("平台线程");
        // 虚拟线程
        Thread.Builder virtualBuilder = Thread.ofVirtual().name("虚拟线程");

        platformBuilder.start(() -> {System.out.println("平台线程");});
        virtualBuilder.start(() -> {System.out.println("虚拟线程");});
    }

    public static void platOrVirtuallyCompare(){
        final AtomicInteger atomicInteger = new AtomicInteger();
        Runnable runnable = () -> {
            try {
                Thread.sleep(Duration.ofSeconds(1));
            } catch(Exception e) {
                System.out.println(e);
            }
            atomicInteger.incrementAndGet();
//            System.out.println("Work Done - " + );
        };

        // 平台线程
        Instant start = Instant.now();
        try (var executor = Executors.newFixedThreadPool(100)) {
            for(int i = 0; i < 1_000; i++) {
                executor.submit(runnable);
            }
        }
        Instant finish = Instant.now();
        long timeElapsed = Duration.between(start, finish).toMillis();
        System.out.println("总耗时 : " + timeElapsed);

        // 虚拟线程
        start = Instant.now();
        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
            for(int i = 0; i < 1_000; i++) {
                executor.submit(runnable);
            }
        }
        finish = Instant.now();
        timeElapsed = Duration.between(start, finish).toMillis();
        System.out.println("总耗时 : " + timeElapsed);

    }


}
